    //
//  CantonAndVocViewController.m
//  WRY
//
//  Created by zhong sckj on 10-10-19.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "EnterpriseListVC_iPad.h"
#import "EnterpriseListView.h"
#import "AppDelegate_iPad.h"
#import "CommonJson.h"
#import "WebPath.h"
//#include "math.h"
#import "StaticVariable.h"

//全局变量
extern NSString *namecode;
extern NSString *nameStr;

@implementation EnterpriseListVC_iPad
@synthesize enterlistView;
@synthesize listData,coverImagesArray,listCategoryData,listVocatondata;
@synthesize afopenflowview;
@synthesize wrydetailTypeCode,selectName;
@synthesize rootVc;
@synthesize image1,image2,image3,image4;
@synthesize segmentController,localmapView,enterlistDiect,keyArray;
@synthesize delegate,mapModeView;
@synthesize btnStandard,btnSatellite;
@synthesize isMapLoad;

///国控 ，省控
-(void)requestForLevel
{
	[self showLoading:512.0 centerY:350.0];
	NSString *methodvocationName=@"Statistic__EnterpriseLevel";
	NSString *bodyStr = [NSString stringWithFormat:@"LoginGuid=%@&LevelCode=",[[AppDelegate_iPad currentDelegate] GUID]];
	bodyStr = [bodyStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	[[CommonJson sharedInstance] requestToPath:[WebPath enterprisePath]
									methodName:methodvocationName 
									bodyString:bodyStr 
									 targetObj:self
							  targetMethodName:@"eventForLevel:"
									notifiName:@"statistic_Level"];
	
}
- (void)eventForLevel:(NSNotification *)notification {
	[self hideLoading];
	[[CommonJson sharedInstance] removeTarget:self notiName:[notification name]];
	NSObject *object  = [notification object];
	if ([object isKindOfClass:[NSDictionary class]])
	{
		NSDictionary *dict = (NSDictionary *)object;
		if ([[dict objectForKey:@"Status"] intValue]) 
		{
			if ([[dict objectForKey:@"Data"] isKindOfClass:[NSArray class]])
			{
				[listCategoryData removeAllObjects];
				NSArray *data=(NSArray *)[dict objectForKey:@"Data"];
				[listCategoryData setArray:data];
				[self drawfourImage:4];
				[self coverflowAction];
			}
		}
	}
}

//行业统计
- (void)requestForVocation{
	[self showLoading:512.0 centerY:350.0];
	NSString *methodvocationName=@"Statistic__EnterpriseVocation";
	NSString *bodyStr = [NSString stringWithFormat:@"LoginGuid=%@&VocationCode=",[[AppDelegate_iPad currentDelegate] GUID]];
	bodyStr = [bodyStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	[[CommonJson sharedInstance] requestToPath:[WebPath enterprisePath]
									methodName:methodvocationName 
									bodyString:bodyStr 
									 targetObj:self
							  targetMethodName:@"eventForVocation:"
									notifiName:@"statistic_Vocation"];
	
}
- (void)eventForVocation:(NSNotification *)notification {
	[self hideLoading];
	[[CommonJson sharedInstance] removeTarget:self notiName:[notification name]];
	NSObject *object  = [notification object];
	if ([object isKindOfClass:[NSDictionary class]])
	{
		NSDictionary *dict = (NSDictionary *)object;
		if ([[dict objectForKey:@"Status"] intValue]) 
		{
			if ([[dict objectForKey:@"Data"] isKindOfClass:[NSArray class]])
			{
				[listVocatondata removeAllObjects];
				NSArray *data=(NSArray *)[dict objectForKey:@"Data"];
				[listVocatondata setArray:data];
				[self drawfourImage:3];
				[self coverflowAction];
			}
		}
	}
}
//行政区
- (void)requestForRegion:(NSString *)body methodName:(NSString *)mthod {
	[self showLoading:512.0 centerY:350.0];
	NSString *bodyStr = [NSString stringWithFormat:@"LoginGuid=%@&%@",[[AppDelegate_iPad currentDelegate] GUID],body];
	bodyStr = [bodyStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	[[CommonJson sharedInstance] requestToPath:[WebPath enterprisePath]
									methodName:mthod 
									bodyString:bodyStr 
									 targetObj:self
							  targetMethodName:@"eventForRequest:"
									notifiName:@"detail_withDay"];
	
}
- (void)eventForRequest:(NSNotification *)notification {
	[self hideLoading];
	[[CommonJson sharedInstance] removeTarget:self notiName:[notification name]];
	NSObject *object  = [notification object];
	if ([object isKindOfClass:[NSDictionary class]])
	{
		NSDictionary *dict = (NSDictionary *)object;
		if ([[dict objectForKey:@"Status"] intValue]) 
		{
			if ([[dict objectForKey:@"Data"] isKindOfClass:[NSArray class]])
			{
				[listData removeAllObjects];
				NSArray *data=(NSArray *)[dict objectForKey:@"Data"];
				[listData setArray:data];
				[self drawfourImage:1];
				[self drawfourImage:2];
				[self coverflowAction];
			}
		}
	}
}
-(void)linkData
{
	NSString *body;
	if (wrydetailTypeCode==1000) {
		body = [NSString stringWithFormat:@"CantonCodes=%@",namecode];
		self.selectName=nameStr;
	}
	else {
		body = [NSString stringWithFormat:@"CantonCodes=%@",[[AppDelegate_iPad currentDelegate]userCantonCodes]];
		self.selectName=[[AppDelegate_iPad currentDelegate]showCantonName];
	}
	NSString *methodName=@"Statistic__EnterpriseCantonRealTime";
	[self requestForRegion:body methodName:methodName];
	[self requestForVocation];//请求行业类别
	[self requestForLevel];//请求关注类型
}

-(void)initLeftView
{
	UIImageView *leftframeView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0,10,648)];
	[leftframeView setImage:[UIImage imageNamed:@"indexframe.png"]];
	[self.view addSubview:leftframeView];
	[leftframeView release];
	
	
	//[self linkData];
	
}
#pragma mark coverflow Delegate
- (void)openFlowView:(AFOpenFlowView *)openFlowView requestImageForIndex:(int)index{
	//NSLog(@"request image for index called");
	//[openFlowView setImage:[UIImage imageNamed:@"default.jpg"] forIndex:3];
	[afopenflowview reloadInputViews];
}
- (void)openFlowView:(AFOpenFlowView *)openFlowView selectionDidChange:(int)index{
	//NSLog(@"selection did change called");
}
-(void)openFlowView: (AFOpenFlowView *)openFlowView imageSelected:(int)index
{
    
}
- (UIImage *)defaultImage
{
	//NSLog(@"default call");
	return [UIImage imageNamed:@"testleftIndex.png"];
}
-(void)coverflowAction
{
	
	[coverImagesArray removeAllObjects];
	if (image1!=nil) {
		[coverImagesArray addObject:image1];
	}
	if (image2!=nil) 
		[coverImagesArray addObject:image2];
	if (image3!=nil) 
		[coverImagesArray addObject:image3];
	if (image4!=nil) 
		[coverImagesArray addObject:image4];

	[afopenflowview setNumberOfImages:[coverImagesArray count]];
	for (int i=0;i<[coverImagesArray count];i++) {
		UIImage *im=[self.coverImagesArray objectAtIndex:i];
		[afopenflowview setImage:im forIndex:i];
	}
	[afopenflowview setSelectedCover:0];
	[afopenflowview centerOnSelectedCover:YES];
}
#pragma mark 刷新更新页面内容
-(void)reloadPageEntList:(NSInteger)fromType enterType:(NSString *)enterpriseType
{
	//entertype 1000调用企业列表 其它调用行业列表
	[enterlistView reflurbish:fromType enterType:enterpriseType];//更新污染源列表
	wrydetailTypeCode=fromType;
	[self linkData];
}
-(void)createMapMode
{
	segmentController=[[UISegmentedControl alloc]initWithItems:[NSArray arrayWithObjects:@"查看统计图",@"查看地图",nil]];
	[segmentController setFrame:CGRectMake(20, 15.0, 207.0, 44.0)];
	[self.view addSubview:segmentController];
	[segmentController addTarget:self action:@selector(segmentChange:) 
				forControlEvents:UIControlEventValueChanged];
	
	mapModeView=[[UIView alloc]initWithFrame:CGRectMake(300.0, 20.0, 122, 29.0)];
	UIButton *btnmode1=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 61.0, 29.0)];
	[btnmode1 setTitle:@"地图" forState:UIControlStateNormal];
	btnmode1.tag=1;
	[btnmode1 setBackgroundImage:[UIImage imageNamed:@"btn61x29.png"] 
						forState:UIControlStateNormal];
	[btnmode1 addTarget:self action:@selector(changeMapMode:) 
	   forControlEvents:UIControlEventTouchUpInside];
	self.btnStandard=btnmode1;
	[btnmode1 release];
	[mapModeView addSubview:btnStandard];
	
	UIButton *btnmode2=[[UIButton alloc]initWithFrame:CGRectMake(61.0, 0, 61.0, 29.0)];
	[btnmode2 setTitle:@"卫星" forState:UIControlStateNormal];
	[btnmode2 setBackgroundImage:[UIImage imageNamed:@"btn60x29.png"] 
						forState:UIControlStateNormal];
	btnmode2.tag=2;
	[btnmode2 addTarget:self action:@selector(changeMapMode:) 
	   forControlEvents:UIControlEventTouchUpInside];
	self.btnSatellite=btnmode2;
	[btnmode2 release];
	[mapModeView addSubview:btnSatellite];
    mapModeView.hidden=YES;
	[self.view addSubview:mapModeView];
	[mapModeView release];
	
	self.mapModeView.hidden=YES;
}
-(void)segmentChange:(id)sender
{
	if (segmentController.selectedSegmentIndex==0) {
		[afopenflowview setHidden:NO];
		[localmapView setHidden:YES];
		[mapModeView setHidden:YES];
	}
	else {
		
		if (!isMapLoad) {
			[self setMapPorperites];
		}
		isMapLoad=YES;
		[afopenflowview setHidden:YES];
		if (localmapView.hidden==YES) {
			[localmapView setHidden:NO];
			[mapModeView setHidden:NO];
		}
		
	}
}
#pragma mark 更改地图模式
-(void)changeMapMode:(id)sender
{
	UIButton *btn=(UIButton *)sender;
	if (btn.tag==1) {
		//地图
		self.localmapView.mapType=MKMapTypeStandard;
		[self.btnStandard setBackgroundImage:[UIImage imageNamed:@"btn61x29_h.png"] 
									forState:UIControlStateNormal];
		[self.btnSatellite setBackgroundImage:[UIImage imageNamed:@"btn60x29.png"] 
									 forState:UIControlStateNormal];
	}
	else {
		self.localmapView.mapType=MKMapTypeSatellite;
		[self.btnStandard setBackgroundImage:[UIImage imageNamed:@"btn61x29.png"] 
									forState:UIControlStateNormal];
		[self.btnSatellite setBackgroundImage:[UIImage imageNamed:@"btn60x29_h.png"] 
									 forState:UIControlStateNormal];
	}

}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad 
{
    [super viewDidLoad];
	CGRect rect=CGRectMake(0, 100, 1024, 648);
	self.view.frame=rect;
	listData=[[NSMutableArray alloc]init];
	listVocatondata=[[NSMutableArray alloc]init];
	listCategoryData=[[NSMutableArray alloc]init];
	
	coverImagesArray=[[NSMutableArray alloc]init];
	
	//地图
	localmapView=[[MKMapView alloc]initWithFrame:CGRectMake(10, 10, 720, 638)];
	localmapView.delegate=self;
    localmapView.hidden=YES;
	[self.view addSubview:localmapView];
	
	//加载coverflower
	afopenflowview=[[AFOpenFlowView alloc]initWithFrame:CGRectMake(10.0,20.0,720,648)];
	afopenflowview.viewDelegate=self;
	afopenflowview.dataSource=self;
	[self.view addSubview:afopenflowview];
	
	//加载enterpriseListView
	EnterpriseListView *enterlist=[[EnterpriseListView alloc]initWithFrame:CGRectMake(736,10, 284, 648) loadFromType:2 entertype:wrydetailTypeCode];
	enterlist.rootVc=self.rootVc;
	enterlist.listVcController=self;
	self.enterlistView=enterlist;
	[enterlist release];
	[self.view addSubview:enterlistView];
	
	//加载选择地图模式的view
	[self createMapMode];
	segmentController.selectedSegmentIndex=0;
	
	//加载coverflow的数据
	[self initLeftView];
	
    //加载地图
	self.keyArray=[[NSArray alloc]init];
	self.enterlistDiect=[[NSMutableDictionary alloc]init];
	isMapLoad=NO;
}
-(void)drawfourImage:(NSInteger)imageindex
{	
	UIView *statis_PicView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 502, 533)];
	[statis_PicView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"right540x571_3.png"]]];
	
	UILabel *lblTitle=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 502, 40)];
	lblTitle.backgroundColor=[UIColor clearColor];
	lblTitle.textColor=[UIColor whiteColor];
	lblTitle.font=[UIFont boldSystemFontOfSize:16.0];
	lblTitle.textAlignment=UITextAlignmentCenter;
	[statis_PicView addSubview:lblTitle];
	
	
	if (imageindex==1) {
		//添加标题
		lblTitle.text=[NSString stringWithFormat:@"%@污染源在线监测概况饼图",self.selectName];
		//文字说明
		UITextView *messageLabel=[[UITextView alloc]initWithFrame:CGRectMake(40, 400, 420,120)];
		messageLabel.text=[self setSummaryText];
		messageLabel.font=[UIFont boldSystemFontOfSize:13.0];
		messageLabel.scrollEnabled=YES;
		messageLabel.tag=20;
		[statis_PicView addSubview:messageLabel];
		[messageLabel release];
		
		//画实时污染源扇形
		UIView *sectorview=[self drawSector:1]; 
		sectorview.tag=40;
		[statis_PicView addSubview:sectorview];
		//将view转换成image
		self.image1=[self imageWithUIView:statis_PicView];
	}
	else if(imageindex==2) {
		
		lblTitle.text=@"按企业类型统计污染源情况";
		//画柱状图(废水，废气，污水厂)
		UIView *histogramView=[self drawHistogramView];
		[statis_PicView addSubview:histogramView];
		self.image2=[self imageWithUIView:statis_PicView];
	}
	else if(imageindex==3)
	{
		lblTitle.text=@"按行业类别统计污染源情况";
		//画标题
		//按行业画柱状图
		UIView *vocationzhuView=[self drawVocationView];
		[statis_PicView addSubview:vocationzhuView];
		self.image3=[self imageWithUIView:statis_PicView];
	}
	else{
		lblTitle.text=@"按关注类型统计污染源情况";
		//画标题
		//按级别画柱状图
		UIView *levelzhuView=[self drawLevelView];
		[statis_PicView addSubview:levelzhuView];
		self.image4=[self imageWithUIView:statis_PicView];
	}
	[lblTitle release];
	[statis_PicView release];

}
- (UIImage*) imageWithUIView:(UIView*) view
{
    // 创建一个bitmap的context  
    // 并把它设置成为当前正在使用的context  
    UIGraphicsBeginImageContext(view.bounds.size);  
    
    CGContextRef ctx = UIGraphicsGetCurrentContext();
	
    //[view.layer drawInContext:ctx];
    [view.layer renderInContext:ctx];
	
    // 从当前context中创建一个改变大小后的图片  
    UIImage* tImage = UIGraphicsGetImageFromCurrentImageContext();  
    
    // 使当前的context出堆栈  
    UIGraphicsEndImageContext();  
    return tImage;
} 
-(UIView *)drawLevelView
{
	NSMutableArray *dataarray=[[NSMutableArray alloc]init];
	
	for (NSDictionary * dir in self.listCategoryData) 
	{
		
		NSString *levelName=[dir objectForKey:@"LevelName"];
		NSString *chaobiao=[dir objectForKey:@"SuperscaleCount"];
		NSString *guzhang=[dir objectForKey:@"TroubleCount"];
		NSString *total=[dir objectForKey:@"EnterpriseCount"];
		NSString *zhengchang=[NSString stringWithFormat:@"%d",
							  [total intValue]-[chaobiao intValue]-[guzhang intValue]];
		SC_StackBarChartData* statckbarChar=[[SC_StackBarChartData alloc]init];
		statckbarChar.title=levelName;
		statckbarChar.over=[chaobiao intValue];
		statckbarChar.normal=[zhengchang intValue];
		statckbarChar.closed=[guzhang intValue];
		[dataarray addObject:statckbarChar];
		[statckbarChar release];
	}
	SC_StackBarChartVC *stackVc=[[SC_StackBarChartVC alloc]init];
	[stackVc setViewFrame:CGRectMake(50.0, 100,400,300)];
	[stackVc.view setBackgroundColor:[UIColor clearColor]];
	[stackVc touchEnabled:NO];
	[stackVc resetData:dataarray];
	[dataarray release];
	return stackVc.view;
}
-(UIView *)drawVocationView
{
	NSMutableArray *dataarray=[[NSMutableArray alloc]init];
	
	for (NSDictionary * dir in self.listVocatondata) 
	{
	
			NSString *vocationName=[dir objectForKey:@"VocationName"];
			NSString *chaobiao=[dir objectForKey:@"SuperscaleCount"];
			NSString *guzhang=[dir objectForKey:@"TroubleCount"];
			NSString *total=[dir objectForKey:@"EnterpriseCount"];
			NSString *zhengchang=[NSString stringWithFormat:@"%d",
								  [total intValue]-[chaobiao intValue]-[guzhang intValue]];
			SC_StackBarChartData* statckbarChar=[[SC_StackBarChartData alloc]init];
			statckbarChar.title=vocationName;
			statckbarChar.over=[chaobiao intValue];
			statckbarChar.normal=[zhengchang intValue];
			statckbarChar.closed=[guzhang intValue];
			[dataarray addObject:statckbarChar];
			[statckbarChar release];
	}
	SC_StackBarChartVC *stackVc=[[SC_StackBarChartVC alloc]init];
	[stackVc setViewFrame:CGRectMake(20.0,100.0,480,300)];//zl 1028 ,450.0f
	[stackVc.view setBackgroundColor:[UIColor clearColor]];
	[stackVc touchEnabled:NO];
	[stackVc resetData:dataarray];
	[dataarray release];
	return stackVc.view;
	
}
#pragma mark -画实时扇形
-(UIView *)drawSector:(NSInteger)detailtypeCode
{
	pieChartController= [[SC_PieChartVC alloc] init];
	[pieChartController setViewFrame:CGRectMake(50.0, 80.0,400,300)];
	[(SC_PieView *)pieChartController.view setDelegate:self];
	
	SC_PieChartData *data = [[SC_PieChartData alloc] init];
	NSMutableArray *dataArray = [[NSMutableArray alloc] init];
	
	
	int zhengchang;
	int chaobiao;
	int lixian;
	
	zhengchang=[[(NSDictionary *)[listData objectAtIndex:0] objectForKey:@"NormalCount"] intValue];
	chaobiao=[[(NSDictionary *)[listData objectAtIndex:0] objectForKey:@"SuperscaleCount"]intValue];
	lixian=[[(NSDictionary *)[listData objectAtIndex:0] objectForKey:@"TroubleCount"]intValue];
	data.value =zhengchang;
	data.title = @"正常";
	//data.color = [UIColor greenColor];
	[dataArray addObject:data];
	data = [[SC_PieChartData alloc] init];
	data.value = chaobiao;
	data.title = @"超标";
	//data.color = [UIColor orangeColor];
	[dataArray addObject:data];
	data = [[SC_PieChartData alloc] init];
	data.value = lixian;
	data.title = @"离线";
	//data.color = [UIColor blueColor];
	[dataArray addObject:data];
	[data release];
	[pieChartController setData:dataArray];
	[dataArray release];
	//[cv release];
	return pieChartController.view;
}
#pragma mark SC_PieViewDelegate
- (void)needReloadMarkersFor:(NSArray *)dataArray Dots:(NSArray *)dotArray {
	//NSArray *array = [cv getDotArray];
	for (UIView *view in pieChartController.view.subviews) {
		[view removeFromSuperview];
	}
	float total = 0.0f;
	for (SC_PieChartData * data in dataArray) {
		total += data.value;
	}
	for (int i = 0; i < [dotArray count]; i ++) 
	{
        
		SC_PieChartData *data = [dataArray objectAtIndex:i];
        if (data.value<=0) {
            continue;
        }
        
		SC_PieChartMarkerView *marker = [[SC_PieChartMarkerView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 182.0f,82.0f)];
		 marker.transform=CGAffineTransformMakeScale(0.8, 0.8);
		[pieChartController.view addSubview:marker];
		
		marker.titleLabel.text = data.title;
		marker.countLabel.text = [NSString stringWithFormat:@"%.0f个(%.0f%%)",data.value,data.value/total * 100];
		//marker.overLabel.text = [NSString stringWithFormat:@"超标"];
		if (data.overValue > 0.0f) {
			marker.overLabel.text = [NSString stringWithFormat:@"超标：%ld",(long)data.overValue];
		}
		NSDictionary *dict = [dotArray objectAtIndex:i];
		float x = [[dict objectForKey:@"x"] floatValue];
		float y = [[dict objectForKey:@"y"] floatValue];
		CGSize size = pieChartController.view.bounds.size;
        marker.center = CGPointMake(x,y);
		NSString *imageName=@"";
		NSString *direction=@"";
		if (x < size.width / 2.0f && y < size.height / 2.0f) {
			imageName = @"right182x82.png";
			direction = @"DownRight";  
          
		}
		else if (x < size.width / 2.0f && y > size.height / 2.0f) {
			imageName = @"right182x82_2.png";
			direction = @"UpRight";
		}
		else if (x > size.width / 2.0f && y < size.height / 2.0f) {
			imageName = @"left182x82.png";
			direction = @"DownLeft";
		}
		else if (x > size.width / 2.0f && y > size.height / 2.0f) {
			imageName = @"left182x82_2.png";
			direction = @"UpLeft";
		}
		[marker.markerImage setImage:[UIImage imageNamed:imageName]];
		[marker setDirectionString:direction];
		[marker setNeedsDisplay];
		[marker release];
	}
	
}

#pragma mark -
#pragma mark 废水，废气，污水厂 超标，故障，停产
-(UIView *)drawHistogramView
{
	NSMutableArray *dataarray=[[NSMutableArray alloc]init];
	
	NSDictionary *dict;
	NSDictionary *directFeiShui=nil;
	NSDictionary *directFeiqi=nil;
	NSDictionary *directWushui=nil;
	NSDictionary *directTotal=nil;
	for (int i=0; i<[listData count]; i++) {
		NSString *enterpriseType=[(NSDictionary *)[listData objectAtIndex:i] objectForKey:@"DetailTypeCode"];
		NSDictionary *direct=(NSDictionary *)[listData objectAtIndex:i];
		if ([enterpriseType isEqualToString:@"01"]) {
			//废水
			directFeiShui=direct;
		}
		else if([enterpriseType isEqualToString:@"02"])
		{
			directFeiqi=direct;
		}
		else if([enterpriseType isEqualToString:@"03"])
		{
			directWushui=direct;
		}
		else {
			directTotal=direct;
		}
		
	}
   
	//废水污染源
    if (![directFeiShui isKindOfClass:[NSNull class]] && directFeiShui !=nil) {
        NSString *feishuizhengchang=[directFeiShui objectForKey:@"NormalCount"];
        NSString *feishuichaobiao=[directFeiShui objectForKey:@"SuperscaleCount"];
        NSString *feishuiguzhang=[directFeiShui objectForKey:@"TroubleCount"];
        
        dict=[[NSDictionary alloc]initWithObjectsAndKeys:@"废水",@"name",feishuizhengchang,@"zhengchang",feishuichaobiao,@"chaobiao",
              feishuiguzhang,@"guzhang",nil];
        [dataarray addObject:dict];
        [dict release];
    }
	
    if (![directFeiqi isKindOfClass:[NSNull class]] && directFeiqi !=nil) {
        //废气污染源
        NSString *feiqizhengchang=[directFeiqi objectForKey:@"NormalCount"];
        NSString *feiqichaobiao=[directFeiqi objectForKey:@"SuperscaleCount"];
        NSString *feiqiguzhang=[directFeiqi objectForKey:@"TroubleCount"];
        
        dict=[[NSDictionary alloc]initWithObjectsAndKeys:@"废气",@"name",feiqizhengchang,@"zhengchang",feiqichaobiao,@"chaobiao",
              feiqiguzhang,@"guzhang",nil];
        [dataarray addObject:dict];
        [dict release];
    }
	 if (![directWushui isKindOfClass:[NSNull class]] && directWushui !=nil) {
         //污水厂
         NSString *wushuichangzc=[directWushui objectForKey:@"NormalCount"];
         NSString *wushuichangcb=[directWushui objectForKey:@"SuperscaleCount"];
         NSString *wushuichanggz=[directWushui objectForKey:@"TroubleCount"];
         
         dict=[[NSDictionary alloc]initWithObjectsAndKeys:@"污水处理厂",@"name",wushuichangzc,@"zhengchang",wushuichangcb,@"chaobiao",
               wushuichanggz,@"guzhang",nil];
         [dataarray addObject:dict];
         [dict release];
     }
	
	
	
	
	NSMutableArray *stackarray=[[NSMutableArray alloc]init];
	
	for (NSDictionary *dir in dataarray) 
	{
		
		NSString *name=[dir objectForKey:@"name"];
		NSString *zhengchang=[dir objectForKey:@"zhengchang"];
		NSString *chaobiao=[dir objectForKey:@"chaobiao"];
		NSString *guzhang=[dir objectForKey:@"guzhang"];
		
		SC_StackBarChartData* statckbarChar=[[SC_StackBarChartData alloc]init];
		statckbarChar.title=name;
		statckbarChar.over=[chaobiao intValue];
		statckbarChar.normal=[zhengchang intValue];
		statckbarChar.closed=[guzhang intValue];
		[stackarray addObject:statckbarChar];
		[statckbarChar release];
	}
	SC_StackBarChartVC *stackVc=[[SC_StackBarChartVC alloc]init];
	[stackVc setViewFrame:CGRectMake(50.0,100.0,400,300)];
	[stackVc.view setBackgroundColor:[UIColor clearColor]];
	[stackVc touchEnabled:NO];
	[stackVc resetData:stackarray];
	[stackarray release];
	[dataarray release];
	return stackVc.view;	
}
-(NSString *)convetString:(NSString *)inputStr
{
    if (inputStr==nil || [inputStr isKindOfClass:[NSNull class]]) {
        inputStr=@"0";
    }
    return inputStr;
}
- (NSMutableString *)setSummaryText {
	
	NSDictionary *directFeiShui=nil;
	NSDictionary *directFeiqi=nil;
	NSDictionary *directWushui=nil;
	NSDictionary *directTotal=nil;
    NSDictionary *directMetal=nil;//重金属
    
	for (int i=0; i<[listData count]; i++) {
		NSString *enterpriseType=[(NSDictionary *)[listData objectAtIndex:i] objectForKey:@"DetailTypeCode"];
		NSDictionary *direct=(NSDictionary *)[listData objectAtIndex:i];
		if ([enterpriseType isEqualToString:@"01"]) {
			//废水
			directFeiShui=direct;
		}
		else if([enterpriseType isEqualToString:@"02"])
		{
			directFeiqi=direct;
		}
		else if([enterpriseType isEqualToString:@"03"])
		{
			directWushui=direct;
		}
        else if([enterpriseType isEqualToString:@"04"])
		{
			directMetal=direct;
		}
		else if([enterpriseType isEqualToString:@""]){
			directTotal=direct;
		}
		
	}
	NSMutableString *body = [[NSMutableString alloc] init];
   
	[body appendFormat:@"%@共有污染源%@个,",self.selectName,[self convetString:[directTotal objectForKey:@"EnterpriseCount"]]];
	[body appendFormat:@"其中%@个废水污染源,",[self convetString:[directFeiShui objectForKey:@"EnterpriseCount"]]];
	[body appendFormat:@"%@个废气污染源,",[self convetString:[directFeiqi objectForKey:@"EnterpriseCount"]]];
	[body appendFormat:@"%@个污水处理厂,",[self convetString:[directWushui objectForKey:@"EnterpriseCount"]]];
    if (directMetal!=nil) {
		[body appendFormat:@"%@个重金属。",[directMetal objectForKey:@"EnterpriseCount"]];
	}
	[body appendFormat:@"%@个正常,",[self convetString:[directTotal objectForKey:@"NormalCount"]]];
	[body appendFormat:@"%@个超标,",[self convetString:[directTotal objectForKey:@"SuperscaleCount"]]];
	[body appendFormat:@"%@个故障或停产。",[self convetString:[directTotal objectForKey:@"TroubleCount"]]];
	[body appendFormat:@"其中有%@个废水污染源超标,",[self convetString:[directFeiShui objectForKey:@"SuperscaleCount"]]];
	[body appendFormat:@"%@个废水污染源故障或停产;",[self convetString:[directFeiShui objectForKey:@"TroubleCount"]]];
	[body appendFormat:@"%@个废气污染源超标,",[self convetString:[directFeiqi objectForKey:@"SuperscaleCount"]]];
	[body appendFormat:@"%@个废气污染源故障或停产。",[self convetString:[directFeiqi objectForKey:@"TroubleCount"]]];
	[body appendFormat:@"%@个污水处理厂超标,",[self convetString:[directWushui objectForKey:@"SuperscaleCount"]]];
	[body appendFormat:@"%@个污水处理厂故障或停产。",[self convetString:[directWushui objectForKey:@"TroubleCount"]]];
     if (directMetal!=nil) {
         [body appendFormat:@"%@个重金属超标,",[self convetString:[directMetal objectForKey:@"SuperscaleCount"]]];
         [body appendFormat:@"%@个重金属故障或停产。",[self convetString:[directMetal objectForKey:@"TroubleCount"]]];
     }
	return body;
}
#pragma mark 计算两点间得距离
-(double)rad:(double)d 
{  
	
	return d*M_PI/180.0;
	
}  
   
-(double)getDistance:(double) lat1 lng1:(double)lng1
				lat2:(double)lat2 lng2:(double)lng2  
{  
	double EARTH_RADIUS = 6378.137; 
	double radLat1 =[self rad:lat1]; 
	double radLat2 = [self rad:lat2];
	double a = radLat1 - radLat2;  
	double b = [self rad:lng1]-  [self rad:lng2];  
	//double s = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(a/2),2) +   
//			Math.Cos(radLat1)*Math.Cos(radLat2)*Math.Pow(Math.Sin(b/2),2)));
	double s = 2 *asin(sqrt(pow(sin(a/2),2) +cos(radLat1)*cos(radLat2)*pow(sin(b/2),2)));
	
	s = s * EARTH_RADIUS;  
	s = round(s * 10000) / 10000;  
	return s;  
}  
#pragma mark 计算地图中间点得坐标点
-(CGPoint)comparePoint:(NSDictionary *)direct
{
	float minLon,minLat,maxLon,maxLat;
	for (NSString *keys in keyArray) {
		NSArray *dataarray=[direct objectForKey:keys];
		NSDictionary *dict=[dataarray objectAtIndex:0];
		maxLat=[[dict objectForKey:@"EnterpriseLat"] floatValue];
		minLat=[[dict objectForKey:@"EnterpriseLat"] floatValue];
		maxLon=[[dict objectForKey:@"EnterpriseLon"] floatValue];
		minLon=[[dict objectForKey:@"EnterpriseLon"] floatValue];
		break;
	}
	for (NSString *keys in [direct allKeys])
	{
		NSArray *dataarray=[direct objectForKey:keys];
		NSDictionary *dict=[dataarray objectAtIndex:0];
		float latvalue=[[dict objectForKey:@"EnterpriseLat"] floatValue];//纬度
		float longValue=[[dict objectForKey:@"EnterpriseLon"] floatValue];//经度
			if (latvalue>maxLat && latvalue<35) {
				maxLat=latvalue;
			}
			if (latvalue<minLat && latvalue>30) {
				minLat=latvalue;
			}
			if (longValue>maxLon && longValue<122) {
				maxLon=longValue;
			}
			if (longValue<minLon && longValue>117) {
				minLon=longValue;
			}
		
	}
	
	//计算中间点坐标(minlon+maxlon)/2,(minlat+maxlat)/2
	CGPoint point=CGPointMake((minLon+maxLon)/2, (maxLat+minLat)/2);
	
	//最大点和最小点间的距离
	distance=[self getDistance:minLat lng1:minLon 
						  lat2:maxLat lng2:maxLon];
	
	return point;
}
//画地图
- (void)setMapPorperites {
	
    [self.enterlistDiect removeAllObjects];
	for (NSDictionary * dir in enterlistView.listData) {
        //NSLog(@"%d",[enterlistView.listData count]);
		[self.enterlistDiect setObject:[NSArray arrayWithObject:dir] forKey:[dir objectForKey:@"EnterpriseCode"]];
	}
	
	//self.enterlistDiect=enterlistView.entersDir;

	
	self.keyArray=[enterlistDiect allKeys];
	[localmapView removeAnnotations:[localmapView annotations]];
	if (![keyArray count]) {
		return;
	}
	for (NSString * keys in keyArray) 
	{
		 NSArray *arraydata=[enterlistDiect objectForKey:keys];
		 NSDictionary *direct=[arraydata objectAtIndex:0];
	
		
		CLLocationCoordinate2D theCenter;
		float latvalue=[[direct objectForKey:@"EnterpriseLat"] floatValue];
		float longValue=[[direct objectForKey:@"EnterpriseLon"] floatValue];
		if (latvalue<=30 || longValue<=117 || latvalue>=35 || longValue>=122) {
			//处理特殊点
			continue;
		}
		else {
			theCenter.latitude = [[direct objectForKey:@"EnterpriseLat"] floatValue]; 
			theCenter.longitude = [[direct objectForKey:@"EnterpriseLon"] floatValue];
			//加注释
			CLLocationCoordinate2D theCoordinate;
			theCoordinate.latitude =theCenter.latitude ;
			theCoordinate.longitude=theCenter.longitude;
			MapAnnotation * ano = [[MapAnnotation alloc] initWithCoords:theCoordinate name:[direct objectForKey:@"EnterpriseCode"]];
			[localmapView addAnnotation:ano];
			[ano release];
		}
	}
	//添加中心点
	CGPoint point=[self comparePoint:enterlistDiect];
	MKCoordinateRegion theRegin;
	CLLocationCoordinate2D theCenter;
	theCenter.latitude = point.y;
	theCenter.longitude = point.x;
	theRegin.center=theCenter;
	
	//加注释
	CLLocationCoordinate2D theCoordinate;
	theCoordinate.latitude =theCenter.latitude ;
	theCoordinate.longitude=theCenter.longitude;
	MapAnnotation * ano = [[MapAnnotation alloc] initWithCoords:theCoordinate name:@"centerPoint"];
	[localmapView addAnnotation:ano];
	[ano release];
	
	
	MKCoordinateSpan theSpan;
	theSpan.latitudeDelta =distance/111; 
	theSpan.longitudeDelta =distance/111;
//    theSpan.latitudeDelta = 2.7;
//    theSpan.longitudeDelta = 2.7;
	//theSpan.latitudeDelta =1.0;
	//theSpan.longitudeDelta =1.0;
	theRegin.span = theSpan;
	[localmapView setRegion:theRegin];
	[localmapView regionThatFits:theRegin];
	localmapView.showsUserLocation = NO;
}

-(UIImage *)createMarkMapViewImage:(NSDictionary *)direct longatude:(float)longatude
{
	float width=100;
	float height=20;
	float fontsize=12.0;
	NSString *enterpriseName=[direct objectForKey:@"EnterpriseName"];
	CGSize suggestedSize = [enterpriseName sizeWithFont:[UIFont systemFontOfSize:fontsize] constrainedToSize:CGSizeMake(1,FLT_MAX) lineBreakMode:UILineBreakModeTailTruncation];
	if (1.0<=longatude) {
		fontsize=14.0;
		suggestedSize = [enterpriseName sizeWithFont:[UIFont systemFontOfSize:fontsize] constrainedToSize:CGSizeMake(1,FLT_MAX) lineBreakMode:UILineBreakModeTailTruncation];
	}
	else if(0.5<=longatude)
	{
		fontsize=16.0;
		suggestedSize = [enterpriseName sizeWithFont:[UIFont systemFontOfSize:fontsize] constrainedToSize:CGSizeMake(1,FLT_MAX) lineBreakMode:UILineBreakModeTailTruncation];
	}
	else {
		fontsize=18.0;
		suggestedSize = [enterpriseName sizeWithFont:[UIFont systemFontOfSize:fontsize] constrainedToSize:CGSizeMake(1,FLT_MAX) lineBreakMode:UILineBreakModeTailTruncation];
	}
	//label宽度
	width=suggestedSize.height-20;
	height=suggestedSize.width;
	//添加标签
	UIImageView *imageview=[[UIImageView alloc]initWithFrame:CGRectMake(width/2, 15, 16, 37)];
	NSString *enterpriseState=[NSString stringWithFormat:@"%@",[direct objectForKey:@"EnterpriseState"]];
	if ([enterpriseState isEqualToString:@"0"]) {
		//正常
		[imageview setImage:[UIImage imageNamed:@"mapPin2.png"]];
	}
	else if([enterpriseState isEqualToString:@"1"]) {
		//超标
		[imageview setImage:[UIImage imageNamed:@"mapPin.png"]];
	}
	else
	{
		//故障
		[imageview setImage:[UIImage imageNamed:@"mapPin3.png"]];
	}
	UILabel *lbl=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, width, height)];
	[lbl setText:[direct objectForKey:@"EnterpriseName"]];
	[lbl setBackgroundColor:[UIColor blackColor]];
	//[lbl setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"btn154x17.png"]]];
	[lbl setAlpha:0.7];
	[lbl setTextColor:[UIColor whiteColor]];
	[lbl setTextAlignment:UITextAlignmentCenter];
	[lbl setFont:[UIFont systemFontOfSize:fontsize]];
	//[lbl setAlpha:0.6];
	
	UIView *v=[[UIView alloc]initWithFrame:CGRectMake(0, 0, width, height+37)];
	[v addSubview:lbl];
	[lbl release];
	
	[v addSubview:imageview];
	[imageview release];
	
	[v setBackgroundColor:[UIColor clearColor]];
	
	UIImage *imageMark=[self imageWithUIView:v];
	[v release];
	return imageMark;
	
}
#pragma mark MKMapViewdelegate

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
	
	if ([annotation isKindOfClass:[MapAnnotation class]]) {
		
		MapAnnotation *mapAnno = (MapAnnotation *)annotation;
		static NSString *AnoViewIdentifier = @"voucherMapAnoView";
		MKAnnotationView *anoView = [[MKAnnotationView alloc] initWithAnnotation:mapAnno
																 reuseIdentifier:AnoViewIdentifier];
		mapAnno.subName=@" ";
		NSArray *dataarray=[enterlistDiect objectForKey:mapAnno.name];
		if ([dataarray count]>0) {
			NSDictionary *direct=[dataarray objectAtIndex:0];
			//添加title
			//mapAnno.title=[NSString stringWithFormat:@"%@ %@:%@(%@)",[direct objectForKey:@"SiteName"],[direct objectForKey:@"StName"]
            //,[direct objectForKey:@"OverData"],[direct objectForKey:@"UName"]];
			
			
			if (mapView.region.span.longitudeDelta<2.0 || mapView.region.span.latitudeDelta<2.0)
			{
				anoView.image=[self createMarkMapViewImage:direct longatude:mapView.region.span.longitudeDelta];
			}
			else {
				anoView.image=[UIImage imageNamed:@"mapPin2.png"];
			}
		}
		else {
			anoView.image=[UIImage imageNamed:@"mapPin2.png"];
		}
		if ([mapAnno.name isEqualToString:@"centerPoint"])
			anoView.image=nil;
        
        
		if (![keyArray isKindOfClass:[NSNull class]] && [keyArray count]>0) {
			anoView.canShowCallout = YES;
			UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
			[button setFrame:CGRectMake(0, 0, 73, 31)];
			[button setBackgroundImage:[UIImage imageNamed:@"btn(73x31)_h.png"] forState:UIControlStateNormal];
			[button setTitle:@"详情" forState:UIControlStateNormal];
			button.tag=[keyArray indexOfObject:mapAnno.name];
			[button addTarget:self
					   action:@selector(detailbuttonPressed:)
			 forControlEvents:UIControlEventTouchUpInside];
			UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
			button2.frame=CGRectMake(0, 0, 73, 31);
			[button2 setBackgroundImage:[UIImage imageNamed:@"btn(73x31)_h.png"] forState:UIControlStateNormal];
			[button2 setTitle:@"显示" forState:UIControlStateNormal];
			button2.tag=[keyArray indexOfObject:mapAnno.name];
			[button2 addTarget:self action:@selector(navibuttonPressed:) forControlEvents:UIControlEventTouchUpInside];
			anoView.rightCalloutAccessoryView = button;
			anoView.leftCalloutAccessoryView=button2;
			
		}
		return anoView;
	}
	return nil;

}
#pragma mark region改变
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
	float longtude=mapView.region.span.longitudeDelta;
	float lattude=mapView.region.span.latitudeDelta;
	if (longtude<2.0 || lattude<2.0)
	{
		for(MapAnnotation *mapAnno in mapView.annotations)
		{
			
			NSArray *dataarray=[enterlistDiect objectForKey:mapAnno.name];
			NSDictionary *direct=[dataarray objectAtIndex:0];
			MKAnnotationView *anoView=[mapView viewForAnnotation:mapAnno];
			
			UIImage *annotationImage=[self createMarkMapViewImage:direct 
														longatude:longtude];
			anoView.image=annotationImage;
		}
	}
	
}
-(void)detailbuttonPressed:(id)sender
{
	UIButton *btn=(UIButton *)sender;
	NSString *key=[keyArray objectAtIndex:btn.tag];
	
	NSArray *dataarray=[enterlistDiect objectForKey:key];
	if ([dataarray count]>0) {
		NSDictionary *direct=[dataarray objectAtIndex:0];
		[delegate mapbuttonPressedInEnterlist:direct];
	}
	
}
-(void)navibuttonPressed:(id)sender
{
	UIButton *btn=(UIButton *)sender;
	NSString *key=[keyArray objectAtIndex:btn.tag];
	
	NSArray *dataarray=[enterlistDiect objectForKey:key];
	if ([dataarray count]>0) {
		NSDictionary *direct=[dataarray objectAtIndex:0];
		//这里的经纬度和企业详情里的key 不一样 设统一
		//EnterpriseName  EnterpriseLongitude EnterpriseLatitude
		[direct setValue:[direct objectForKey:@"EnterpriseLon"] forKey:@"EnterpriseLongitude"];
		[direct setValue:[direct objectForKey:@"EnterpriseLat"] forKey:@"EnterpriseLatitude"];
		[delegate mapbuttonPressedNavi:direct];
		
	}
	
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
	if (interfaceOrientation==UIInterfaceOrientationLandscapeLeft || interfaceOrientation==UIInterfaceOrientationLandscapeRight)
	{
		return YES;
	}
    else 
	{
		return NO;
	}
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}


- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[btnStandard release];
	[btnSatellite release];
	[mapModeView release];
	[keyArray release];
	//[delegate release];
	[enterlistDiect release];
	[localmapView release];
	[segmentController release];
	[image2 release];
	[image3 release];
	[image4 release];
	[selectName release];
	[listCategoryData release];
	[listVocatondata release];
	[afopenflowview release];
	[coverImagesArray release];
	[listData release];
	[enterlistView release];
    [super dealloc];
}


@end
